document.addEventListener('DOMContentLoaded', function() {
    const parseForm = document.getElementById('parse-form');
    const videoInfoDiv = document.getElementById('video-info');
    const videoTitle = document.getElementById('video-title');
    const videoAuthor = document.getElementById('video-author');
    const videoCover = document.getElementById('video-cover');
    const cidSelect = document.getElementById('cid');
    const qualitySelect = document.getElementById('quality');
    const downloadForm = document.getElementById('download-form');
    const downloadProgress = document.getElementById('download-progress');
    const downloadLink = document.getElementById('download-link');

    // 图片加载错误处理
    let isDefaultImage = false;
    if (videoCover) {
        videoCover.onerror = function() {
            if (!isDefaultImage) {
                isDefaultImage = true;
                this.src = '/static/default-cover.png';
            }
        };
    }

    parseForm.onsubmit = async function(e) {
        e.preventDefault();
        const url = document.getElementById('url').value.trim();
        if (!url) return;
        
        // 隐藏相关区域
        if (videoInfoDiv) videoInfoDiv.style.display = 'none';
        if (downloadLink) downloadLink.style.display = 'none';
        if (downloadProgress) downloadProgress.style.display = 'none';
        
        try {
            // 解析视频
            const resp = await fetch('/api/parse', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({url})
            });
            
            if (!resp.ok) {
                const error = await resp.json();
                throw new Error(error.error || '解析失败');
            }
            
            const data = await resp.json();
            console.log('解析结果:', data);
            
            // 更新视频信息
            if (videoTitle) videoTitle.textContent = data.title;
            if (videoAuthor) videoAuthor.textContent = data.author;
            
            // 重置默认图片标志
            isDefaultImage = false;
            // 使用新的图片获取接口
            if (videoCover) videoCover.src = `/api/image/${encodeURIComponent(data.cover)}`;
            
            // 更新分P列表
            if (cidSelect) {
                cidSelect.innerHTML = '<option value="">请选择分P</option>';
                data.parts.forEach(part => {
                    const option = document.createElement('option');
                    option.value = part.cid;
                    option.textContent = part.title;
                    cidSelect.appendChild(option);
                });
            }
            
            // 更新清晰度列表
            if (qualitySelect) {
                qualitySelect.innerHTML = '<option value="">请选择清晰度</option>';
                if (data.qualities && data.qualities.length > 0) {
                    console.log('清晰度列表:', data.qualities);
                    data.qualities.forEach(quality => {
                        const option = document.createElement('option');
                        option.value = quality.value;
                        option.textContent = quality.name;
                        qualitySelect.appendChild(option);
                    });
                } else {
                    console.warn('未获取到清晰度列表');
                }
            }
            
            // 显示视频信息区域
            if (videoInfoDiv) videoInfoDiv.style.display = 'block';
        } catch (error) {
            console.error('解析失败:', error);
            alert(error.message || '解析失败');
        }
    };

    // 更新下载进度
    function updateProgress(taskId) {
        debugger
        const progressDiv = document.getElementById('download-progress');
        const progressBarVideo = document.getElementById('progress-bar-video');
        const progressBarAudio = document.getElementById('progress-bar-audio');
        const currentStep = document.getElementById('current-step');
        const downloadSpeed = document.getElementById('download-speed');
        const downloadStatus = document.getElementById('download-status');
        const loadingSpinner = document.getElementById('loading-spinner');
        
        if (!progressDiv || !progressBarVideo || !progressBarAudio || !currentStep || !downloadSpeed || !downloadStatus || !loadingSpinner) return;
        
        fetch(`/api/progress/${taskId}?t=${Date.now()}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'finished') {
                    // 更新进度条
                    progressBarVideo.style.width = '100%';
                    progressBarVideo.textContent = '100%';
                    progressBarVideo.className = 'progress-bar bg-success';
                    progressBarAudio.style.width = '100%';
                    progressBarAudio.textContent = '100%';
                    progressBarAudio.className = 'progress-bar bg-success';
                    
                    // 更新状态信息
                    currentStep.textContent = '下载完成';
                    downloadStatus.textContent = '状态: 完成';
                    downloadSpeed.textContent = '';
                    loadingSpinner.style.display = 'none';
                    
                    // 显示下载链接
                    const downloadLink = document.getElementById('download-link');
                    if (downloadLink) {
                        downloadLink.style.display = 'block';
                        // 移除可能存在的旧下载按钮
                        const oldButton = downloadLink.querySelector('.download-button');
                        if (oldButton) {
                            oldButton.remove();
                        }
                        
                        // 创建新的下载按钮
                        const downloadButton = document.createElement('a');
                        downloadButton.href = `/api/file/${taskId}`;
                        downloadButton.className = 'download-button';
                        downloadButton.textContent = '下载视频文件';
                        
                        // 添加到下载链接区域
                        const downloadLinkContainer = downloadLink.querySelector('.download-link-container');
                        if (downloadLinkContainer) {
                            downloadLinkContainer.appendChild(downloadButton);
                        }
                    }
                    
                    return;
                }
                
                if (data.status === 'error') {
                    currentStep.textContent = `下载失败: ${data.error}`;
                    downloadStatus.textContent = '状态: 失败';
                    progressBarVideo.className = 'progress-bar bg-danger';
                    progressBarAudio.className = 'progress-bar bg-danger';
                    loadingSpinner.style.display = 'none';
                    return;
                }
                
                // 更新视频进度条
                const videoProgress = data.video_progress || [0, 1];
                const videoPercent = Math.round(videoProgress[1] ? videoProgress[0] / videoProgress[1] * 100 : 0);
                progressBarVideo.style.width = videoPercent + '%';
                progressBarVideo.textContent = videoPercent + '%';
                // 更新音频进度条
                const audioProgress = data.audio_progress || [0, 1];
                const audioPercent = Math.round(audioProgress[1] ? audioProgress[0] / audioProgress[1] * 100 : 0);
                progressBarAudio.style.width = audioPercent + '%';
                progressBarAudio.textContent = audioPercent + '%';
                
                // 更新当前步骤和状态
                if (data.current_step && data.current_step.includes('合并')) {
                    currentStep.textContent = '视频音频合成处理中';
                    loadingSpinner.style.display = 'inline-block';
                    downloadStatus.textContent = '状态: 音视频合成中';
                    downloadSpeed.textContent = '';
                } else {
                    currentStep.textContent = data.current_step || '正在下载...';
                    loadingSpinner.style.display = 'none';
                    // 更新下载速度
                    const speed = (data.total_speed / 1024 / 1024).toFixed(2);
                    downloadSpeed.textContent = `下载速度: ${speed} MB/s`;
                    downloadStatus.textContent = `状态: ${data.status === 'running' ? '下载中' : '等待中'}`;
                }
                
                // 继续轮询
                setTimeout(() => updateProgress(taskId), 1000);
            })
            .catch(error => {
                console.error('获取进度失败:', error);
                currentStep.textContent = '获取进度失败';
                downloadStatus.textContent = '状态: 错误';
                progressBarVideo.className = 'progress-bar bg-danger';
                progressBarAudio.className = 'progress-bar bg-danger';
                loadingSpinner.style.display = 'none';
            });
    }

    // 视频开始下载
    downloadForm.onsubmit = async (e) => {
        e.preventDefault();
        
        const url = document.getElementById('url').value;
        const quality = document.getElementById('quality').value;
        const cid = document.getElementById('cid').value;
        const danmaku = document.getElementById('danmaku').checked;
        const subtitle = document.getElementById('subtitle').checked;
        
        try {
            const response = await fetch('/api/download', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({
                    url,
                    quality,
                    cid,
                    danmaku,
                    subtitle
                })
            });
            
            const data = await response.json();
            
            if (data.error) {
                alert(data.error);
                return;
            }
            
            // 显示进度条
            const progressDiv = document.getElementById('download-progress');
            if (progressDiv) {
                progressDiv.style.display = 'block';
            }
            
            // 开始更新进度
            updateProgress(data.task_id);
            
        } catch (error) {
            console.error('下载失败:', error);
            alert('下载失败: ' + error.message);
        }
    };

}); 